<template>
  <div class="login">
    <!-- 背景动画元素 -->
    <div class="background-animation">
      <div class="shape circle"></div>
      <div class="shape triangle"></div>
      <div class="shape square"></div>
      <div class="shape rectangle"></div>
      <div class="shape pentagon"></div>
      <div class="shape hexagon"></div>
    </div>
    
    <!-- 粒子背景容器 -->
    <div id="particles-js"></div>
    
    <el-form ref="loginForm" :model="loginForm" :rules="loginRules" class="login-form">
      <div class="login-container">
        <div class="login-left">
          <div class="login-title">{{title}}</div>
          <div class="login-desc">
            <p>欢迎使用 Mood Harbor 系统</p>
            <p>请使用您的账户登录</p>
          </div>
        </div>
        <div class="login-right">
          <el-form-item prop="username">
            <el-input
              v-model="loginForm.username"
              type="text"
              auto-complete="off"
              placeholder="账号"
            >
              <svg-icon slot="prefix" icon-class="user" class="el-input__icon input-icon" />
            </el-input>
          </el-form-item>
          <el-form-item prop="password">
            <el-input
              v-model="loginForm.password"
              type="password"
              auto-complete="off"
              placeholder="密码"
              @keyup.enter.native="handleLogin"
            >
              <svg-icon slot="prefix" icon-class="password" class="el-input__icon input-icon" />
            </el-input>
          </el-form-item>
          <el-form-item prop="code" v-if="captchaEnabled">
            <el-input
              v-model="loginForm.code"
              auto-complete="off"
              placeholder="验证码"
              style="width: 63%"
              @keyup.enter.native="handleLogin"
            >
              <svg-icon slot="prefix" icon-class="validCode" class="el-input__icon input-icon" />
            </el-input>
            <div class="login-code">
              <img :src="codeUrl" @click="getCode" class="login-code-img"/>
            </div>
          </el-form-item>
          <el-checkbox v-model="loginForm.rememberMe" style="margin:0px 0px 25px 0px;">记住密码</el-checkbox>
          <el-form-item style="width:100%;">
            <el-button
              :loading="loading"
              size="medium"
              type="primary"
              style="width:100%;"
              @click.native.prevent="handleLogin"
            >
              <span v-if="!loading">登 录</span>
              <span v-else>登 录 中...</span>
            </el-button>
            <div style="float: right;" v-if="register">
              <router-link class="link-type" :to="'/register'">立即注册</router-link>
            </div>
          </el-form-item>
        </div>
      </div>
    </el-form>
    <!--  底部  -->
    <div class="el-login-footer">
      <span>Copyright © 2018-2025DUUDU All Rights Reserved.</span>
    </div>
  </div>
</template>

<script>
import { getCodeImg } from "@/api/login"
import Cookies from "js-cookie"
import { encrypt, decrypt } from '@/utils/jsencrypt'

export default {
  name: "Login",
  data() {
    return {
      title: process.env.VUE_APP_TITLE,
      codeUrl: "",
      loginForm: {
        username: "admin",
        password: "admin123",
        rememberMe: false,
        code: "",
        uuid: ""
      },
      loginRules: {
        username: [
          { required: true, trigger: "blur", message: "请输入您的账号" }
        ],
        password: [
          { required: true, trigger: "blur", message: "请输入您的密码" }
        ],
        code: [{ required: true, trigger: "change", message: "请输入验证码" }]
      },
      loading: false,
      // 验证码开关
      captchaEnabled: true,
      // 注册开关
      register: false,
      redirect: undefined,
      backgroundUrl: ""
    }
  },
  watch: {
    $route: {
      handler: function(route) {
        this.redirect = route.query && route.query.redirect
      },
      immediate: true
    }
  },
  created() {
    this.getBackgroundImage();
    this.getCode()
    this.getCookie()
  },
  mounted() {
    // 加载 particles.js 库
    this.loadParticlesJS();
  },
  methods: {
    // 加载 particles.js 库
    loadParticlesJS() {
      // 创建 script 标签
      const script = document.createElement('script');
      script.src = 'https://cdn.jsdelivr.net/npm/particles.js@2.0.0/particles.min.js';
      script.onload = () => {
        // 库加载完成后初始化粒子效果
        this.initParticles();
      };
      document.head.appendChild(script);
    },
    
    // 初始化粒子效果
    initParticles() {
      if (typeof particlesJS !== 'undefined') {
        particlesJS('particles-js', {
          particles: {
            number: {
              value: 80,
              density: {
                enable: true,
                value_area: 800
              }
            },
            color: {
              value: "#ffffff"
            },
            shape: {
              type: "circle",
              stroke: {
                width: 0,
                color: "#000000"
              }
            },
            opacity: {
              value: 0.5,
              random: false,
              anim: {
                enable: false,
                speed: 1,
                opacity_min: 0.1,
                sync: false
              }
            },
            size: {
              value: 3,
              random: true,
              anim: {
                enable: false,
                speed: 40,
                size_min: 0.1,
                sync: false
              }
            },
            line_linked: {
              enable: true,
              distance: 150,
              color: "#ffffff",
              opacity: 0.4,
              width: 1
            },
            move: {
              enable: true,
              speed: 2,
              direction: "none",
              random: false,
              straight: false,
              out_mode: "out",
              bounce: false,
              attract: {
                enable: false,
                rotateX: 600,
                rotateY: 1200
              }
            }
          },
          interactivity: {
            detect_on: "canvas",
            events: {
              onhover: {
                enable: true,
                mode: "grab"
              },
              onclick: {
                enable: true,
                mode: "push"
              },
              resize: true
            },
            modes: {
              grab: {
                distance: 140,
                line_linked: {
                  opacity: 1
                }
              },
              push: {
                particles_nb: 4
              }
            }
          },
          retina_detect: true
        });
      }
    },
    
    // 获取背景图片
    getBackgroundImage() {
      fetch('https://api.bimg.cc/random?w=1920&h=1080&mkt=zh-CN')
        .then(response => {
          if (response.ok) {
            return response.blob();
          }
          throw new Error('Network response was not ok.');
        })
        .then(blob => {
          const backgroundUrl = URL.createObjectURL(blob);
          this.backgroundUrl = backgroundUrl;
          // 设置背景图片
          document.querySelector('.login').style.backgroundImage = `url(${backgroundUrl})`;
        })
        .catch(error => {
          console.error('获取背景图片失败:', error);
          // 如果获取失败，使用默认背景
          document.querySelector('.login').style.backgroundImage = "url('../assets/images/login-background.jpg')";
        });
    },
    getCode() {
      getCodeImg().then(res => {
        this.captchaEnabled = res.captchaEnabled === undefined ? true : res.captchaEnabled
        if (this.captchaEnabled) {
          this.codeUrl = "data:image/gif;base64," + res.img
          this.loginForm.uuid = res.uuid
        }
      })
    },
    getCookie() {
      const username = Cookies.get("username")
      const password = Cookies.get("password")
      const rememberMe = Cookies.get('rememberMe')
      this.loginForm = {
        username: username === undefined ? this.loginForm.username : username,
        password: password === undefined ? this.loginForm.password : decrypt(password),
        rememberMe: rememberMe === undefined ? false : Boolean(rememberMe)
      }
    },
    handleLogin() {
      this.$refs.loginForm.validate(valid => {
        if (valid) {
          this.loading = true
          if (this.loginForm.rememberMe) {
            Cookies.set("username", this.loginForm.username, { expires: 30 })
            Cookies.set("password", encrypt(this.loginForm.password), { expires: 30 })
            Cookies.set('rememberMe', this.loginForm.rememberMe, { expires: 30 })
          } else {
            Cookies.remove("username")
            Cookies.remove("password")
            Cookies.remove('rememberMe')
          }
          this.$store.dispatch("Login", this.loginForm).then(() => {
            this.$router.push({ path: this.redirect || "/" }).catch(()=>{})
          }).catch(() => {
            this.loading = false
            if (this.captchaEnabled) {
              this.getCode()
            }
          })
        }
      })
    }
  }
}
</script>

<style rel="stylesheet/scss" lang="scss">
.login {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100%;
  background-image: url("../assets/images/login-background.jpg");
  background-size: cover;
  overflow: hidden;
  position: relative;
}

// 背景动画元素
.background-animation {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  z-index: 0;
}

.shape {
  position: absolute;
  opacity: 0.6;
  filter: blur(1px);
}

.circle {
  width: 80px;
  height: 80px;
  border-radius: 50%;
  background: linear-gradient(45deg, #409eff, #64b5f6);
  top: 10%;
  left: 10%;
  animation: float 8s infinite ease-in-out;
}

.triangle {
  width: 0;
  height: 0;
  border-left: 40px solid transparent;
  border-right: 40px solid transparent;
  border-bottom: 70px solid #4caf50;
  top: 20%;
  right: 10%;
  animation: float 10s infinite ease-in-out;
  animation-delay: 1s;
}

.square {
  width: 70px;
  height: 70px;
  background: linear-gradient(45deg, #ff9800, #ffc107);
  bottom: 15%;
  left: 15%;
  animation: float 9s infinite ease-in-out;
  animation-delay: 2s;
}

.rectangle {
  width: 100px;
  height: 60px;
  background: linear-gradient(45deg, #f44336, #e91e63);
  top: 40%;
  right: 20%;
  animation: float 12s infinite ease-in-out;
  animation-delay: 0.5s;
}

.pentagon {
  position: relative;
  width: 54px;
  border-width: 50px 18px 0;
  border-style: solid;
  border-color: #9c27b0 transparent;
  top: 25%;
  left: 25%;
  animation: float 11s infinite ease-in-out;
  animation-delay: 1.5s;
}

.pentagon:before {
  content: "";
  position: absolute;
  height: 0;
  width: 0;
  top: -85px;
  left: -18px;
  border-width: 0 45px 35px;
  border-style: solid;
  border-color: transparent transparent #9c27b0;
}

.hexagon {
  width: 60px;
  height: 35px;
  background: #03a9f4;
  position: relative;
  top: 60%;
  left: 40%;
  animation: float 13s infinite ease-in-out;
  animation-delay: 2.5s;
}

.hexagon:before {
  content: "";
  position: absolute;
  top: -17px;
  left: 0;
  width: 0;
  height: 0;
  border-left: 30px solid transparent;
  border-right: 30px solid transparent;
  border-bottom: 17px solid #03a9f4;
}

.hexagon:after {
  content: "";
  position: absolute;
  bottom: -17px;
  left: 0;
  width: 0;
  height: 0;
  border-left: 30px solid transparent;
  border-right: 30px solid transparent;
  border-top: 17px solid #03a9f4;
}

@keyframes float {
  0% {
    transform: translate(0, 0) rotate(0deg);
  }
  25% {
    transform: translate(20px, 20px) rotate(90deg);
  }
  50% {
    transform: translate(40px, 0) rotate(180deg);
  }
  75% {
    transform: translate(20px, -20px) rotate(270deg);
  }
  100% {
    transform: translate(0, 0) rotate(360deg);
  }
}

.login-container {
  display: flex;
  width: 100%;
  height: 100%;
  min-height: 450px;
  position: relative;
  z-index: 2;
}

.login-left {
  flex: 1;
  background-color: rgba(64, 158, 255, 0.8);
  border-top-left-radius: 6px;
  border-bottom-left-radius: 6px;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  color: white;
}

.login-title {
  font-size: 32px;
  font-weight: bold;
  margin-bottom: 20px;
}

.login-desc {
  font-size: 16px;
  text-align: center;
}

.login-desc p {
  margin: 10px 0;
}

.login-right {
  flex: 1;
  padding: 40px;
  background: #ffffff;
  border-top-right-radius: 6px;
  border-bottom-right-radius: 6px;
  display: flex;
  flex-direction: column;
  justify-content: center;
}

.login-form {
  border-radius: 6px;
  width: 100%;
  max-width: 800px;
  z-index: 1;
  box-shadow: 0 0 20px rgba(0, 0, 0, 0.1);
}

.el-input {
  height: 38px;
  input {
    height: 38px;
  }
}

.input-icon {
  height: 39px;
  width: 14px;
  margin-left: 2px;
}

.login-tip {
  font-size: 13px;
  text-align: center;
  color: #bfbfbf;
}

.login-code {
  width: 33%;
  height: 38px;
  float: right;
  img {
    cursor: pointer;
    vertical-align: middle;
  }
}

.el-login-footer {
  height: 40px;
  line-height: 40px;
  position: fixed;
  bottom: 0;
  width: 100%;
  text-align: center;
  color: #fff;
  font-family: Arial;
  font-size: 12px;
  letter-spacing: 1px;
  z-index: 2;
}

.login-code-img {
  height: 38px;
}

@media screen and (max-width: 768px) {
  .login-container {
    flex-direction: column;
  }
  
  .login-left {
    border-top-left-radius: 6px;
    border-top-right-radius: 6px;
    border-bottom-left-radius: 0;
    padding: 20px 0;
  }
  
  .login-right {
    border-bottom-left-radius: 6px;
    border-bottom-right-radius: 6px;
    border-top-right-radius: 0;
    padding: 20px;
  }
}

// 粒子背景样式
#particles-js {
  position: absolute;
  width: 100%;
  height: 100%;
  background-color: transparent;
  background-image: url("");
  background-repeat: no-repeat;
  background-size: cover;
  background-position: 50% 50%;
  z-index: 0;
}
</style>